﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ThunderRoad;
using UnityEngine;

namespace CultivationSkills.Utils;

public class ResourceAddress : Attribute
{
    public string Value { get; set; }

    public ResourceAddress(string value)
    {
        Value = value;
    }
}

public enum MyAudios
{
    [ResourceAddress("BBY.Audio.Charge")] Charge,
    [ResourceAddress("BBY.Audio.Blink")] Blink,
    [ResourceAddress("BBY.Audio.ChuJian")] ChuJian,
    [ResourceAddress("BBY.Audio.JianQi")] JianQi,
    [ResourceAddress("BBY.Audio.Shoot")] Shoot
}

[SuppressMessage("ReSharper", "IteratorMethodResultIsIgnored")]
public static class MyAssets
{
    private static readonly Dictionary<MyAudios, AudioClip> AudioClips = new Dictionary<MyAudios, AudioClip>();

    public static void PlayAudioOnPlayer(MyAudios audio)
    {
        if (!Player.local)
        {
            return;
        }
        PlayAudio(audio,Player.local.transform.position);
    }

    public static void PlayAudio(MyAudios audio, Vector3 position)
    {
        Debug.Log("PlayAudio：" + audio);
        if (!AudioClips[audio])
        {
            Debug.LogWarning("资源未加载！");
            return;
        }

        PlayClip(AudioClips[audio], position);
    }

    public static void PlayClipOnPlayer(AudioClip clip)
    {
        if (!clip || !Player.local)
        {
            return;
        }

        PlayClip(clip, Player.local.transform.position);
    }

    public static void PlayClip(AudioClip clip, Vector3 position)
    {
        if (!clip)
        {
            return;
        }

        AudioSource.PlayClipAtPoint(clip, position);
    }

    public static void Load()
    {
        foreach (var fieldInfo in typeof(MyAudios).GetFields())
        {
            Console.WriteLine(fieldInfo.Name);
            if (!(Attribute.GetCustomAttribute(fieldInfo, typeof(ResourceAddress)) is ResourceAddress attribute))
                continue;
            var audio = (MyAudios)fieldInfo.GetValue(null);
            var addr = attribute.Value;
            LoadAudioItem(audio, addr);
        }
    }

    private static void LoadAudioItem(MyAudios audio, string addr)
    {
        Debug.Log($"Load Asset %{audio}:%{addr}");
        Catalog.LoadAssetAsync(addr,
            (Action<AudioClip>)(audioClip =>
            {
                Debug.Log($"Load Result: {audioClip}");
                AudioClips.Add(audio, audioClip);
            }), nameof(MyAssets));
    }

    public static void Clear()
    {
    }

    public static AudioClip GetClip(MyAudios audio)
    {
        return AudioClips[audio];
    }
}